package com.dp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dp.dto.Result;
import com.dp.entity.Shop;
import com.dp.mapper.ShopMapper;
import com.dp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dp.utils.CacheClient;
import com.dp.utils.RedisData;
import com.dp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.dp.utils.RedisConstants.*;
import static com.dp.utils.SystemConstants.DEFAULT_PAGE_SIZE;

/**
 * <p>
 * 服务实现类
 * </p>
 *

 */
@Service
@Slf4j
@Transactional
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    //缓存商户信息  redis
    @Override
    public Result queryById(Long id) {
        //缓存穿透
//        Shop shop = queryWithPassThrough(id);

        //用互斥锁解决缓存击穿
//        Shop shop = queryWithMutex(id);
//        Shop shop = queryWithLogicalExpire(id);

        Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class,
                this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        return Result.ok(shop);
    }

    @Override
    public Result update(Shop shop) {
        //1.更新数据库
        this.updateById(shop);
        //2. 删除缓存
        if (shop.getId() == null) {
            return Result.fail("店铺为空");
        }
        stringRedisTemplate.delete(CACHE_SHOP_KEY + shop.getId());
        return Result.ok();
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //1. 判断是否需要根据坐标查询
        if (x==null||y==null){
            // 不需要查询坐标 按照数据库查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current,DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        //2.计算分页参数   current页码   from开始  end结束
        int from = (current - 1) * DEFAULT_PAGE_SIZE;
        int end = current * DEFAULT_PAGE_SIZE;

        //3. 查询redis 按照距离排序 分页  shopId, distance
        // GEOSEARCH key BYLONLAT x y BYRADIUS 10 WITHDISTANCE
        String key=SHOP_GEO_KEY+typeId;   //typeId 店铺类型
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(
                key,
                GeoReference.fromCoordinate(x, y),
                new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeCoordinates().
                        limit(end)
        );
        //4.解析出id
        if (results==null){
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = results.getContent();
        List<Long> ids = new ArrayList<>(content.size());
        HashMap<String, Distance> distanceMap =  new HashMap<>();
        if (content.size()<=from){
            //没有下一页
            return Result.ok(Collections.emptyList());
        }
        //4.1 截取 from-end 的部分
        content.stream().skip(from).forEach(result->{
            String name = result.getContent().getName(); //获取店铺id
            ids.add(Long.valueOf(name));
            Distance distance = result.getDistance(); //获取距离
            distanceMap.put(name,distance);
        });

        //5. 根据id查询shop
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        for (Shop shop : shops) {
            shop.setDistance(distanceMap.get(shop.getId().toString()).getValue());
        }
        // 6.返回
        return Result.ok(shops);
    }

    //上锁
    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.
                opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    //释放锁
    private void unlock(String key) {
        stringRedisTemplate.delete(key);
    }

    // 解决缓存穿透问题
    public Shop queryWithPassThrough(Long id) {
        //1. 从redis  查询商户缓存
        String shopJoson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);

        //2. 判断是否存在
        if (StrUtil.isNotBlank(shopJoson)) {
            //3. 存在直接返回
            Shop shop = JSONUtil.toBean(shopJoson, Shop.class);
            return shop;
        }
        //判断 命中 是否为空值
        if (shopJoson != null) {
            //返回一个错误信息
            return null;
        }

        //4. 不存在根据id 查mysql数据库
        Shop shop = this.getById(id);
        //5. 不存再 返回错误
        if (shop == null) {
            // TODO  解决缓存穿透
            // 将空值 写入redis
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY, "", CACHE_NULL_TTL, TimeUnit.MINUTES);

            // 返回 错误信息

            return null;
        }
        //6. 存在 写入redis
        String toJsonStr = JSONUtil.toJsonStr(shop);
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, toJsonStr, CACHE_SHOP_TTL, TimeUnit.MINUTES);
        log.info("商品已经缓存进redis");

        //7. 再返回
        return shop;
    }

    // 利用互斥锁解决缓存击穿问题
    public Shop queryWithMutex(Long id) {
        //1. 从redis  查询商户缓存
        String shopJoson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);

        //2. 判断是否存在
        if (StrUtil.isNotBlank(shopJoson)) {
            //3. 存在直接返回
            Shop shop = JSONUtil.toBean(shopJoson, Shop.class);
            return shop;
        }
        //判断 命中 是否为空值
        if (shopJoson != null) {
            //返回一个错误信息
            return null;
        }
        //4. 实现缓存重建
        // 4.1 获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean b = tryLock(lockKey);
        // 4.2 判断是否成功
        Shop shop = null;
        try {
            if (!b) {
                // 4.3 失败则休眠并重试
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            //注意 获取锁成功应该再次检测redis 缓存是否存在 做DoubleCheck. 如果存在则无需重建缓存
            String s1 = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
            //2. 判断是否存在
            if (StrUtil.isNotBlank(s1)) {
                //3. 存在直接返回
                Shop shop1 = JSONUtil.toBean(s1, Shop.class);
                return shop1;
            }

            // 4.4 redis未命中 再根据id查询数据库
            shop = this.getById(id);
            Thread.sleep(200);

            //5. 不存再 返回错误
            if (shop == null) {
                // TODO  解决缓存穿透
                // 将空值 写入redis
                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY, "", CACHE_NULL_TTL, TimeUnit.MINUTES);

                return null;
            }
            //6. 存在 写入redis
            String toJsonStr = JSONUtil.toJsonStr(shop);
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, toJsonStr, CACHE_SHOP_TTL, TimeUnit.MINUTES);
            log.info("商品已经缓存进redis");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 7.释放互斥锁
            unlock(lockKey);
        }
        // 8.再返回
        return shop;
    }

    // 线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    // 利用逻辑过期解决缓存击穿问题
    public Shop queryWithLogicalExpire(Long id) {
        //1. 从redis  查询商户缓存
        String shopJoson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);

        //2. 判断是否存在     逻辑过期意味着永不过期
        if (StrUtil.isBlank(shopJoson)) {
            //3. 不存在直接null
            return null;
        }
        //4.命中 先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJoson, RedisData.class);
        Object data = redisData.getData();
        Shop shop = JSONUtil.toBean((JSONObject) data, Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        //5.判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //5.1 未过期返回商品信息
            return shop;
        }
        //5.2 已过期 需要缓存重建
        //6. 缓存重建
        //6.1 获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        //6.2 判断是否获取锁成功
        try {
            if (isLock) {
                //注意 获取锁成功应该再次检测redis 缓存是否存在 做DoubleCheck. 如果存在则无需重建缓存
                String s1 = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);
                //  判断是否存在
                if (StrUtil.isNotBlank(s1)) {
                    //3. 存在直接返回
                    Shop shop1 = JSONUtil.toBean(s1, Shop.class);
                    return shop1;
                }
                //6.3成功 开启独立线程 实现缓存重建
                CACHE_REBUILD_EXECUTOR.submit(()->{
                    // 重建缓存
                    this.saveShop2Redis(id,20L);
                });
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }finally {
            //释放锁
            unlock(lockKey);
        }
        //6.4 返回过期的商铺信息
        return shop;
    }

    //缓存重建
    public void saveShop2Redis(Long id, Long expireSeconds) {
        //1. 查询店铺数据
        Shop shop = this.getById(id);
        //2. 封装逻辑过期
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //3. 写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

}
